package com.leo.demo._07.deadlock;

public class DeadLock04 {
    public static void main(String[] args) {
        Account a = new Account();
        Account b = new Account();
        a.transfer(b,100);
        b.transfer(a,200);
    }
}

class Account {
    private int id;
    private int balance;
    void transfer(Account target, int amt){
        Account left = this;
        Account right = target;
        //这里确保资源是有序的
        if (this.id > target.id) {
            left = target;
            right = this;
        }
        //重要的是这一段，按顺序获取资源
        synchronized(left){
            synchronized(right){
                if (this.balance > amt){
                    this.balance -= amt;
                    target.balance += amt;
                }
            }
        }
    }
}